package hlhj.fhp.newslib.activitys

import android.content.Intent
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import com.google.gson.Gson
import com.lzy.okgo.model.Response
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.GSYVideoHelper
import com.tenma.ventures.bean.utils.TMSharedPUtil
import com.tenma.ventures.config.TMConstant
import com.tenma.ventures.config.TMServerConfig
import com.tenma.ventures.share.bean.TMLinkShare
import com.tenma.ventures.share.util.TMShareUtil
import hlhj.fhp.newslib.BaseAty
import hlhj.fhp.newslib.Constant
import hlhj.fhp.newslib.R
import hlhj.fhp.newslib.adapters.CommentAdp
import hlhj.fhp.newslib.customview.GoLoginDialog
import hlhj.fhp.newslib.javabean.*
import hlhj.fhp.newslib.network.*
import hlhj.fhp.newslib.utils.ToastUtil
import kotlinx.android.synthetic.main.aty_sepcial_info.*
import kotlinx.android.synthetic.main.hlhj_news_head_lo.*
import tmproject.hlhj.fhp.adplayerhelper.AdHelper
import java.util.ArrayList

/**
 * Created by Administrator on 2018\6\25 0025.
 */
class SpecialInfoAty :BaseAty() {
    private val datas=ArrayList<CommentBean.DataBean>()
    private lateinit var adp:CommentAdp
    private var canSend=true
    private var tittleStr=""
    private var des=""
    private var isColl=false
    private var sid=""
    private var itemId=-1
    private var thumb:String?=""
    private var extendStr=""

    private var videoUrl=""
    private var advUrl=""
    override fun initListener() {
        btBack.setOnClickListener {
            finish()
        }
        btGoShare.setOnClickListener {
            val tmLinkShare = TMLinkShare()
            tmLinkShare.title=tittleStr
            tmLinkShare.url= TMServerConfig.BASE_URL+"/application/hlhj_news/asset/article.html?id=${itemId}"
//                    tmLinkShare.url="http://mx.360tianma.com"+"/application/hlhj_news/asset/article.html?id=${item.id}"
            tmLinkShare.description=tittleStr
            if (thumb?.contains("http")!!){
                tmLinkShare.thumb=thumb

            }else{
                tmLinkShare.thumb=Urls.Base_URL+"/"+thumb

            }
            TMShareUtil.getInstance(this).shareLink(tmLinkShare)
        }
        btColl.setOnClickListener {
            val tmUser = TMSharedPUtil.getTMUser(this)
            if (!isColl){
                Apis.collect(tmUser.member_code,
                        tittleStr,
                        Urls.APPID,
                        itemId.toString(),
                        TMSharedPUtil.getTMToken(this@SpecialInfoAty)
                        ,thumb,
                        1,
                        extendStr
//                        "/application/hlhj_news/asset/article.html?id=${itemId}"
                )
                        .doOnSubscribe {
                            loadingDialog.show()
                        }
                        .subscribe ({
                            data->
                            loadingDialog.dismiss()

                            if (data.code==200){
                                val gson = Gson()
                                val bean = gson.fromJson(gson.toJson(data), CollBean::class.java)
                                sid=bean.data.star_id.toString()
                                isColl=true
                                btColl.setImageResource(R.drawable.ic_sc_select)
                            }else{
                                if (data.code==500){
                                    GoLoginDialog(this).show()
                                }else{
                                    Toast.makeText(this@SpecialInfoAty,data.msg,Toast.LENGTH_SHORT).show()
                                }
                            }
                        },{
                            err->
                            loadingDialog.dismiss()
                            err.printStackTrace()
                            Log.e("fhpp","啥子错嘛"+err.toString())
                        })
            }else{
                Apis.cancleCollect(sid,TMSharedPUtil.getTMToken(this@SpecialInfoAty))
                        .doOnSubscribe { loadingDialog.show() }
                        .subscribe ({
                            data->
                            loadingDialog.dismiss()
                            if (data.code==200){
                                btColl.setImageResource(R.drawable.ic_sc_normal)
                                isColl=false
                            }else{
                                Toast.makeText(this@SpecialInfoAty,data.msg,Toast.LENGTH_SHORT).show()
                            }
                        },{
                            erro->{
                            loadingDialog.dismiss()
                        }
                        })
            }

        }
        btExit.setOnClickListener {
            finish()
        }
        btMore.setOnClickListener {
            val i = Intent(this, CommentAty::class.java)
            i.putExtra("id",itemId)
            startActivity(i)
        }
        btSend.setOnClickListener {
            if (etContent.text.isEmpty()){
                ToastUtil.toast("评论内容不能为空")
            }else{
                if (!canSend){
                    ToastUtil.toast("评论内容超过字数限制")
                    return@setOnClickListener
                }
                val tmUser = TMSharedPUtil.getTMUser(this)
                Apis.doComment(itemId,tmUser.member_id,etContent.text.toString(),
                        TMSharedPUtil.getTMToken(this),"")
                        .doOnSubscribe {
                            Log.e("fhp","什么情况1")
                            loadingDialog.show()
                        }
                        .subscribe {
                            body->
                            Log.e("fhp","什么情况2")
                            loadingDialog.dismiss()
                            if (body.code==1){
                                ToastUtil.toast("评论成功")
                                datas.clear()
                                disPatchComment()
                            }else if (body.code==0){
                                GoLoginDialog(this).show()
                            }else if (body.code==500){
                                GoLoginDialog(this).show()
                            }
                            else{
                                ToastUtil.toast(body.message)
                            }
                            etContent.setText("")
                        }
            }
        }
        etContent.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                numCurrent.text=s?.length.toString()+"/"+100
                canSend = s?.length!! <= 100
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    override fun initView() {
        if (TMSharedPUtil.getTMThemeColor(this).isNotEmpty()) {
            dv1.setBackgroundColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(this)))
        }
        itemId=intent.getIntExtra("id",-1)
        thumb=intent.getStringExtra("thumb")

        if (itemId==-1){
            val jsonStr = intent.getStringExtra("paramStr")
            Log.e("fhp","获取到的Json传参${jsonStr}")
            jsonStr?.let {
                val pBean = Gson().fromJson(it, PBean::class.java)
                itemId=pBean.article_id
                thumb=pBean.thumb
            }
        }
        if (itemId==-1){
            val bundle = intent.extras
            val jsonStr = bundle.getString(TMConstant.BundleParams.MULTI_WINDOW_ARGUMENTS)
            jsonStr?.let {
                val pBean = Gson().fromJson(it, PBean::class.java)
                itemId=pBean.article_id
                thumb=pBean.thumb
            }
        }

        val pBean1 = PBean()
        pBean1.article_id=itemId
        pBean1.thumb=thumb

        val extendBean = ExtendBean()
        val androidInfoBean = ExtendBean.AndroidInfoBean()
        androidInfoBean.isNativeX=true
        androidInfoBean.src="hlhj.fhp.newslib.activitys.SpecialInfoAty"
        androidInfoBean.paramStr="${Gson().toJson(pBean1)}"
        androidInfoBean.wwwFolder=""

        val iosInfoBean = ExtendBean.IosInfoBean()
        iosInfoBean.isNativeX=true
        iosInfoBean.src="HLHJNewDetailsController"
        iosInfoBean.paramStr="${Gson().toJson(pBean1)}"
        iosInfoBean.wwwFolder=""
        extendBean.androidInfo=androidInfoBean
        extendBean.iosInfo=iosInfoBean
        extendStr=Gson().toJson(extendBean)
        Log.e("fhppp","自己包装的json${extendStr}")
        tvTittle.text="详情"
        webView.settings.javaScriptEnabled=true
        webView.webViewClient=object :WebViewClient(){
            override fun onPageFinished(view: WebView?, url: String?) {
                tv_C.visibility=View.VISIBLE
                comment_list.visibility=View.VISIBLE
                super.onPageFinished(view, url)
            }
        }
        webView.webChromeClient=object :WebChromeClient(){}

        /*评论*/
        adp=CommentAdp(R.layout.news_comment_item,datas)
        comment_list.adapter=adp
        comment_list.layoutManager=LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)

        judgeColl()
        disPatchData()
        videoPlayer.backButton.visibility=View.GONE

    }

    private fun addHis(){
        val tmUser = TMSharedPUtil.getTMUser(this)
        Apis.addHis(tmUser.member_code,
                tittleStr,
                Urls.APPID,
                itemId.toString(),
                TMSharedPUtil.getTMToken(this@SpecialInfoAty)
                ,thumb,
                1,
                extendStr)
                ?.let {
                    it.doOnSubscribe { }
                            .subscribe{
                                data->

                            }
                }

    }

    private fun judgeColl() {
        val tmUser = TMSharedPUtil.getTMUser(this)

        Apis.isColl(tmUser.member_code,"hlhj.fhp.newslib",itemId.toString(),this)
                .doOnSubscribe { loadingDialog.show() }
                .subscribe({
                    data->
                    loadingDialog.dismiss()
                    try {
                        val bean = Gson().fromJson(data, CollBean::class.java)
                        if (bean.code==200){
                            if (bean?.msg?.contains("未")!!){
                                btColl.setImageResource(R.drawable.ic_sc_normal)
                                isColl=false
                            }else{
                                sid=bean.data.star_id.toString()
                                btColl.setImageResource(R.drawable.ic_sc_select)
                                isColl=true
                            }
                        }
                    }catch (e :Exception){
                        val bean = Gson().fromJson(data, CollBean2::class.java)
                        if (bean.code==200){
                            btColl.setImageResource(R.drawable.ic_sc_normal)
                            isColl=false
                        }
                    }
                })
    }

    private fun disPatchData() {
        /*详情*/
        Apis.getInfoDetail(itemId)
                .doOnSubscribe(LoadingAction(this))
                .subscribe(object :CustomAction<Response<InfoDetailBean>>{
                    override fun onResult(t: Response<InfoDetailBean>) {
                        loadingDialog.dismiss()
                        val detailBean = t.body().data
                        tv_Tittle.text=detailBean.title
                        tittleStr=detailBean.title
                        tvTittleTextView.text=tittleStr
                        des=detailBean.title
//                        tv_Time.text="${detailBean.add_time}                   浏览量：${detailBean.click_rate+1}"
                        tv_Time.text="${detailBean.add_time}"
                        if (detailBean.video_url==null||detailBean.video_url.isEmpty()){
                            videoFather.visibility=View.GONE
                        }else{
                            videoFather.visibility=View.VISIBLE
                            videoUrl=detailBean.video_url
                            val helper = GSYVideoHelper.GSYVideoHelperBuilder()
                            helper
                                    .setHideStatusBar(true)
                                    .setNeedLockFull(true)
                                    .setCacheWithPlay(true)
                                    .setUrl(detailBean.video_url)
                                    .setVideoTitle(detailBean.title)
                                    .setAutoFullWithSize(true)
                                    .build(videoPlayer)

                            AdHelper.setAdPlayer(this@SpecialInfoAty,videoPlayer,videoFather as ViewGroup,Constant.ads,0.7f,0.8f)
                            /*videoPlayer.fullscreenButton.setOnClickListener {
                                videoPlayer.startWindowFullscreen(this@SpecialInfoAty,false,true)
                            }*/
//OnPause的功能
                        }
                        var prompt = detailBean!!.content
                        prompt=prompt.replace("<img", "<img style='max-width:100%;height:auto;'")
                        webView.loadDataWithBaseURL(Urls.Base_URL, prompt,"text/html", "utf-8", null)
//                        tv_auther.text="编/责：${detailBean.release}         编审:${detailBean.release}"
                        tv_auther.text="${detailBean.release}"
                        addHis()
                    }
                })
        /*评论*/
        disPatchComment()
    }

    override fun onResume() {
        super.onResume()
        if (videoPlayer.currentState==5){
            val helper = GSYVideoHelper.GSYVideoHelperBuilder()
            helper
                    .setHideStatusBar(true)
                    .setNeedLockFull(true)
                    .setCacheWithPlay(true)
                    .setUrl(videoUrl)
                    .setVideoTitle(des)
                    .setAutoFullWithSize(true)
                    .build(videoPlayer)

            AdHelper.setAdPlayer(this@SpecialInfoAty,videoPlayer,videoFather as ViewGroup,Constant.ads,0.7f,0.8f)
        }else{
            videoPlayer.onVideoResume()
        }
    }
    override fun onPause() {
        super.onPause()
        videoPlayer.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }

    private fun disPatchComment() {
        Apis.getCommentList(itemId,TMSharedPUtil.getTMToken(this@SpecialInfoAty))
                .doOnSubscribe(LoadingAction(this))
                .subscribe(object : CommentListAction<CommentBean>(this){
                    override fun onResult(data: CommentBean) {
                        loadingDialog.dismiss()
                        if (data.code==1){
                            if (data.data.size > 3) {
                                datas.add(data.data[0])
                                datas.add(data.data[1])
                                datas.add(data.data[2])
                                btMore.visibility=View.VISIBLE
                                adp.notifyDataSetChanged()
                            } else {
                                datas.addAll(data.data)
                                adp.notifyDataSetChanged()
                                btMore.visibility = View.GONE
                            }
                        }else{
//                            ToastUtil.toast(data.message)
                        }
                    }
                })
    }

    override fun getContentId(): Int {
        return R.layout.aty_sepcial_info
    }
}